<?php

declare(strict_types=1);

namespace Modules\User\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;
use Modules\User\Events\AdminBehaviorEvent;
use Modules\User\Models\LogBehavior;

/**
 * 管理员行为监听器
 */
//class AdminBehaviorListener implements ShouldQueue
//{
//    use InteractsWithQueue;
class AdminBehaviorListener
{
    use InteractsWithQueue;

    /**
     * 创建事件监听器
     */
    public function __construct()
    {
        //
    }

    /**
     * 处理事件
     *
     * @param AdminBehaviorEvent $event
     * @return void
     */
    public function handle(AdminBehaviorEvent $event): void
    {
        try {
            $this->doLog($event);
        } catch (\Exception $e) {
            // 记录错误日志但不抛出异常，避免影响主业务流程
            Log::error('AdminBehaviorListener记录日志失败：' . $e->getMessage(), [
                'action' => $event->action,
                'ip' => $event->operateIp,
                'creator_id' => $event->creatorId,
            ]);
        }
    }

    /**
     * 记录管理员行为日志
     *
     * @param AdminBehaviorEvent $event
     * @return void
     */
    protected function doLog(AdminBehaviorEvent $event): void
    {
        $currentTime = time();
        LogBehavior::create([
            'action'     => $event->action,
            'module'     => $event->behavior['module'],
            'business'   => $event->behavior['business'],
            'operation'  => $event->behavior['operation'],
            'related_id' => $event->behavior['related_id'],
            'remark'     => $event->behavior['remark'],
            'operate_ip'    => $event->operateIp,
            'creator_id' => $event->creatorId,
        ]);
    }

    /**
     * 当任务失败时调用
     *
     * @param AdminBehaviorEvent $event
     * @param \Throwable $exception
     * @return void
     */
    public function failed(AdminBehaviorEvent $event, \Throwable $exception): void
    {
        Log::error('AdminBehaviorListener任务失败：' . $exception->getMessage(), [
            'action' => $event->action,
            'ip' => $event->operateIp,
            'creator_id' => $event->creatorId,
        ]);
    }
}
